<template>
  <div class="user-management">
    <el-card>
      <h2>用户信息管理</h2>
      <!-- 搜索栏 -->
      <el-row :gutter="10" class="search-row">
        <el-col :span="5">
          <el-select
            v-model="searchLabel"
            placeholder="选择用户听歌标签"
            @change="searchUser"
            clearable
          >
            <el-option label="所有" value=""></el-option>
            <el-option label="传统音乐类" value="传统音乐类"></el-option>
            <el-option label="新国风流行类" value="新国风流行类"></el-option>
            <el-option label="戏曲融合类" value="戏曲融合类"></el-option>
            <el-option label="主题文化类" value="主题文化类"></el-option>
            <el-option label="地域特色类" value="地域特色类"></el-option>
          </el-select>
        </el-col>
        <el-col :span="5">
          <el-input
            placeholder="输入用户名查询"
            v-model="searchName"
            @keyup.enter="searchUser"
            clearable
          ></el-input>
        </el-col>
        <!-- 用户状态选择框 -->
        <el-col :span="5">
          <el-select
            v-model="searchStatus"
            placeholder="选择用户状态"
            @change="searchUser"
            clearable
          >
            <el-option label="所有" value=""></el-option>
            <el-option label="正常" value="正常"></el-option>
            <el-option label="封禁" value="封禁"></el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="searchUser" style="width: 100%;">查询</el-button>
        </el-col>
        <el-col :span="4">
          <el-button type="success" @click="sendNotification" style="width: 100%;">发送通知</el-button>
        </el-col>
      </el-row>

      <!-- 用户信息表格 -->
      <el-table
        :data="filteredUsers"
        @selection-change="handleSelectionChange"
        style="width: 100%;"
        stripe
        highlight-current-row
        border
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column label="序号" type="index" width="80" align="center"></el-table-column>
        <el-table-column prop="user_name" label="用户名" width="140" align="center"></el-table-column>
        <el-table-column prop="music_label" label="音乐标签" width="200" align="center"></el-table-column>
        <el-table-column prop="country_region" label="国家地区" width="160" align="center"></el-table-column>
        <el-table-column prop="violation_count" label="用户违规次数" width="150" align="center"></el-table-column>
        <el-table-column prop="user_status" label="状态" width="100" align="center"></el-table-column>
        <el-table-column prop="create_date" label="注册时间" width="180" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.create_date) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button size="mini" @click="goToUserInformationDetailManage(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <el-pagination
        small
        layout="prev, pager, next"
        :total="totalUsers"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      />
    </el-card>
  </div>
</template>

<script>
import { ElMessageBox, ElMessage } from 'element-plus'; // 引入 Element-Plus 组件

export default {
  data() {
    return {
      searchLabel: '',           // 用户标签搜索框
      searchName: '',         // 用户名搜索框
      searchStatus: '',       // 用户状态搜索框
      users: [],              // 存储用户数据
      pageSize: 5,            // 每页显示条数
      currentPage: 1,         // 当前页号
      selectedUsers: [],      // 选中的用户
      totalUsers: 0           // 总用户数
    };
  },
  computed: {
    // 计算并过滤符合搜索条件的用户数据
    filteredUsers() {
      return this.users.filter(
        (user) =>
          (!this.searchLabel || user.music_label.toString().includes(this.searchLabel)) &&
          (!this.searchName || user.user_name.includes(this.searchName)) &&
          (!this.searchStatus || user.user_status === this.searchStatus)
      );
    }
  },
  methods: {
    goToUserInformationDetailManage(user){
      const userId = user.user_id;
      this.$router.push({name:'UserInformationDetailManage',params:{userId: userId}})
    },

    // 获取分页数据
    getPageData(page, size) {
      this.$http.get('/v1/user/pages', {
        params: {
          pageNum: page,   // 当前页码
          pageSize: size   // 每页显示的条数
        }
      }).then((response) => {
        if (response.data) {
          this.users = response.data.list;
          this.totalUsers = response.data.total;
        }
      }).catch((error) => {
        console.error('获取用户数据失败:', error);
      });
    },

    // 查询用户
    searchUser() {
      this.getPageData(1, this.pageSize);  // 默认查询第一页的数据
    },
    // 发送通知
    sendNotification() {
      if (this.selectedUsers.length === 0) {
        this.$message.warning('请选择要发送通知的用户！');
        return;
      }

      // 弹出通知输入框
      ElMessageBox.prompt('请输入要发送的通知内容', '发送通知', {
        confirmButtonText: '发送',
        cancelButtonText: '取消',
        inputPlaceholder: '通知内容',
      }).then(({ value }) => {
        if (!value) {
          this.$message.warning('通知内容不能为空！');
          return;
        }

        const user_ids = this.selectedUsers.map(user => user.user_id);

        // 这里需要修改为您的后端接口地址
        const url = '/notifications/admin/bulk'; // 假设您的后端接口是这样的

        this.$http.post(url, {
          user_ids: user_ids,
          content: value,
        })
        .then(() => {
          this.$message.success('通知发送成功！');
        })
        .catch((error) => {
          console.error('通知发送失败:', error);
          this.$message.error('通知发送失败，请稍后重试。');
        });
      }).catch(() => {
        this.$message.info('取消发送通知');
      });
    },

    // 处理多选用户
    handleSelectionChange(val) {
      this.selectedUsers = val;
    },

    // 格式化时间，年月日
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      const year = d.getFullYear();
      const month = ('0' + (d.getMonth() + 1)).slice(-2);
      const day = ('0' + d.getDate()).slice(-2);
      return `${year}-${month}-${day}`;
    },

    // 处理页码变化
    handlePageChange(page) {
      this.currentPage = page;
      this.getPageData(page, this.pageSize);
    }
  },

  mounted() {
    this.getPageData(1, this.pageSize);
  }
}
</script>

<style scoped>
.user-management .el-row {
  margin-bottom: 20px;
}

.el-row .el-col {
  margin-bottom: 10px;
}

.el-button {
  width: 100%;
}

.el-input {
  width: 100%;
}
</style>
